package org.imraniqbal.frogger;

import java.util.Vector;

import org.imraniqbal.engine.Direction;
import org.imraniqbal.engine.Game;
import org.imraniqbal.engine.GameEvent;
import org.imraniqbal.engine.GameListener;
import org.imraniqbal.engine.Map;
import org.imraniqbal.engine.Mappable;
import org.imraniqbal.engine.Player;
/**
 * This is the class representing the frogger player.
 * @author  Colin MacDougall unless otherwise specified
 */
public class Frogger extends Player implements GameListener{
	/**
	 * @uml.property  name="hasFlower"
	 */
	private boolean hasFlower;
	public Frogger(int x, int y) {
		super(x, y);
		setHasFlower(false);
	}

	public Frogger(int x, int y, Direction direction, int numOflives) {
		super(x, y, direction, numOflives);
		setHasFlower(false);
	}

	@Override
	public void spawn(Map map) {
		setX(9);
		setY(9);
		map.addMappable(this);

	}
	/**
	 * @author imran
	 */
	@Override
	public void die(Map map){
		super.die(map);
		if(isHasFlower()){
			setHasFlower(!isHasFlower());
		}
	}
	
	@Override
	public void onEvent(GameEvent e) {
		if( !(e.getSource() instanceof Game)){ return; }
		Game g = (Game) e.getSource();
		Vector<Mappable> m = g.getMap().getMappable(getX(), getY());
		if(m == null){
			return;
		}
		for(int i = 0; i < m.size(); i++){
			Mappable mpl = m.get(i);
			if( mpl instanceof Car){
				this.die(g.getMap());
				if(this.getNumOflives() == 0){
					g.setWin(false);
				}
			}
			else if(mpl instanceof Flower){
				((Flower)mpl).action(this, g.getMap());
			}
			else if( mpl instanceof Home){
				((Home)mpl).action(g, g.getMap());
			}
		}
		//Collision code for tile based games, dealing with things switching spots
		//(this would never be a problem in a non-tile based game)
		
		//universal checking code
		m = g.getMap().getMappable(getOldX(), getOldY());
		if(m == null){ return; }
		for(Mappable mpl : m){
			if( !(mpl instanceof Player) ) { continue; }
			if(((Player)mpl).getOldX() == this.getX() &&
				((Player)mpl).getOldY() == this.getY() ){
				//game specific rule set code below
				this.die(g.getMap());
				if(this.getNumOflives() == 0){
					g.setWin(false);
				}
			}
		}
	}

	/**
	 * @param hasFlower  the hasFlower to set
	 * @author  imran
	 * @uml.property  name="hasFlower"
	 */
	public void setHasFlower(boolean hasFlower) {
		this.hasFlower = hasFlower;
	}

	/**
	 * @return  the hasFlower
	 * @author  imran
	 * @uml.property  name="hasFlower"
	 */
	public boolean isHasFlower() {
		return hasFlower;
	}

}
